package com.kfm.client;

import java.io.IOException;
import java.nio.file.*;
import java.util.List;
public class Watcher {
   public static void main(String[] args) throws IOException {
      // 需要监听的文件目录（只能监听目录）
      String path = "D:/clouder/server";
      WatchService watchService = FileSystems.getDefault().newWatchService();
      Path p = Paths.get(path);
      p.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY,
              StandardWatchEventKinds.ENTRY_DELETE,
              StandardWatchEventKinds.ENTRY_CREATE);
      Thread thread = new Thread(() -> {
         try {
            while (true) {
               WatchKey watchKey = watchService.take();
               List<WatchEvent<?>> watchEvents = watchKey.pollEvents();
               for (WatchEvent<?> watchEvent : watchEvents) {
                  WatchEvent.Kind<?> kind = watchEvent.kind();
                  System.out.println("当前的文件为：" + path + "/" + watchEvent.context() + ", 进行的操作类型为：" + kind);
                  if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                     System.out.println("新建文件: " + watchEvent.context() + " 次数: " + watchEvent.count());
                  } else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
                     System.out.println("删除文件: " + watchEvent.context() + ", 次数: " + watchEvent.count());
                  } else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
                     System.out.println("修改文件: " + watchEvent.context() + ", 次数: " + watchEvent.count());
                  } else if (kind == StandardWatchEventKinds.OVERFLOW) {
                     System.out.println("overflow: " + watchEvent.context() + ", 次数: " + watchEvent.count());
                  }
               }
               watchKey.reset();
            }
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
      });
      thread.setDaemon(false);
      thread.start();

      // 增加jvm关闭的钩子来关闭监听
      Runtime.getRuntime().addShutdownHook(new Thread(() -> {
         try {
            watchService.close();
         } catch (Exception e) {
         }
      }));
   }
}